package com.example.datn.utils;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.example.datn.objects.RssObject;

public class RssHandler extends DefaultHandler {

	public static final String ITEM = "item";
	public static final String TITLE = "title";
	public static final String DESCRIPTION = "description";
	public static final String LINK = "link";
	public static final String DATE = "pubdate";
	private StringBuilder sBuider  = new StringBuilder();

	private RssObject item;
	private List<RssObject> itemList = new ArrayList<RssObject>();
	private boolean started = false;

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
		
		if(started&& (sBuider!=null)){
			sBuider.append(ch, start, length);
			
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub

		super.endElement(uri, localName, qName);

		if (localName.equalsIgnoreCase(ITEM)) {
      
			itemList.add(item);
		}else if (started) {
			if (localName.equalsIgnoreCase(TITLE)) {
				item.setTitle(sBuider.toString().trim());
			} else if (localName.equalsIgnoreCase(DESCRIPTION)) {
				item.setDescription(sBuider.toString().trim());
			} else if (localName.equalsIgnoreCase(LINK)) {
				item.setLink(sBuider.toString().trim());
			} else if (localName.equalsIgnoreCase(DATE)) {
				item.setDate(sBuider.toString().trim());
			}
sBuider =new StringBuilder();
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		super.startElement(uri, localName, qName, attributes);
		if (localName.equalsIgnoreCase(ITEM)) {

			item = new RssObject();
			started = true;

		} 
	}

	public List<RssObject> getItemList() {
		return itemList;
	}

	public void setItemList(List<RssObject> itemList) {
		this.itemList = itemList;
	}
	
	
	
	
	

}
